<template>
  <div class="login">
    <div class="login_box">
      <!-- 头部logo区 -->
      <div class="avatar_box">
        <img src="../assets/logo.png" alt />
      </div>
      <!-- 表单区 -->
      <el-form ref="form" label-width="20px" class="form_box" :model="loginForm" :rules="rules">
        <el-form-item prop="username">
          <el-input prefix-icon="iconfont icon-user" v-model="loginForm.username"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            prefix-icon="iconfont icon-3702mima"
            v-model="loginForm.password"
            type="password"
          ></el-input>
        </el-form-item>
        <div class="form_btn">
          <el-button type="primary" @click="submitForm('form')">提交</el-button>
          <el-button @click="resetForm('form')">重置</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loginForm: {
        username: 'admin',
        password: '123456'
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: 'hahaha', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '密码错误', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 登录函数
    submitForm(form) {
      this.$refs[form].validate(async valid => {
        // 表单验证
        if (!valid) return

        // 发送post请求
        const { data: res } = await this.$http.post('/login', this.loginForm)

        // console.log(res)
        // 结果判断
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)

        // 保存 token 值
        window.sessionStorage.setItem('token', res.data.token)
        this.$router.push('/home')
        this.$message.success(res.meta.msg)
      })
    },
    resetForm(form) {
      // 重置表单
      this.$refs[form].resetFields()
    }
  }
}
</script>

<style lang="less" scoped>
.login {
  height: 100%;
  background-color: #2b4b6b;
  .login_box {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    width: 450px;
    height: 300px;
    background-color: #fff;
    border-radius: 3px;
    .avatar_box {
      position: absolute;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 130px;
      height: 130px;
      background-color: #fff;
      border: 1px solid #eee;
      padding: 10px;
      border-radius: 50%;
      box-shadow: 0 0 10px #eee;
      img {
        width: 100%;
        height: 100%;
        border-radius: 50%;
        background-color: #eee;
      }
    }
  }
  .form_box {
    margin-top: 100px;
    padding-right: 20px;
    .form_btn {
      float: right;
    }
  }
}
</style>
